import redis
from redis import Redis

from Lib.Server import config


class DbRedis:
    def __init__(self):
        self.redis: Redis = redis.Redis(host=config.get("database", "redis_host"),
                                        port=int(config.get("database", "redis_port")),
                                        # password=config.get("database", "redis_password"),
                                        decode_responses=True, db=config.get('database', "redis_db"))

    def ResetListValue(self, list_name: str, source_value: str, to_value: str):
        self.redis.lrem(list_name, 0, source_value)
        self.redis.rpush(list_name, to_value)

    def GetListValueByKey(self, list_name: str, condition_value, str_key: str = "id", return_data=True):
        _list = self.redis.lrange(list_name, 0, -1)
        for item in _list:
            import json
            _item = json.loads(item)
            if _item[str_key] == condition_value:
                return item if return_data else _item
